﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Xml;
using System.Drawing;

namespace QExcel
{
    public class QOutputs
    {
        Workbook book = null;
        ApplicationClass app = null;
        List<QSheet> sheets = new List<QSheet>();
        public List<QSheet> Sheets
        {
            get
            {
                return sheets;
            }
            set
            {
                sheets = value;
            }
        }

        public void Output(string filePath)
        {
            this.CreateApp();
            foreach (QSheet outPut in this.sheets)
            {
                Worksheet workSheet = (Worksheet)book.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workSheet.Name = outPut.SheetText;
                outPut.OutPut(workSheet);
            }

            this.CloseApp(filePath);
        }


        private void CreateApp()
        {
            if (app == null)
            {
                app = new ApplicationClass();
                app.DisplayAlerts = false;
            }

            if (book == null)
            {
                book = app.Workbooks.Add();
            }
        }

        private void CloseApp(string filePath)
        {
            foreach (Worksheet sheet in book.Sheets)
            {
                if (sheet.Name.ToLower() == "sheet1" || sheet.Name.ToLower() == "sheet2" || sheet.Name.ToLower() == "sheet3")
                {
                    sheet.Delete();
                }
            }

            book.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            book.Close();
            app.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        }
    }
}
